<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入菜品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dish:dish:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dish:dish:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="plqs"
          v-hasPermi="['dish:dish:plqs']"
          :disabled="multiple"
        >批量起售
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="plts"
          v-hasPermi="['dish:dish:plts']"
          :disabled="multiple"
        >批量停售
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dish:dish:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dish:dish:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dishList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="菜品名称" align="center" prop="name"/>
      <el-table-column label="图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="菜品分类" align="center" prop="categoryId">
        <template slot-scope="scope">
          <span style="margin-right: 10px;">{{scope.row.category.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label="菜品价格" align="center" prop="price">
        <template slot-scope="scope">
          <span style="margin-right: 10px;">￥{{scope.row.price/100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="售卖状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0" type="info">停售</el-tag>
          <el-tag v-else-if="scope.row.status==1" type="primary">在售</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['dish:dish:plqs']"
            v-if="scope.row.status==0"
            @click="updateStatus(scope.row)"
          >在售
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['dish:dish:plts']"
            v-if="scope.row.status==1"
            @click="updateStatus(scope.row)"
          >停售
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dish:dish:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['dish:dish:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改菜品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜品名称" style="width: 200px"/>
        </el-form-item>
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请输入菜品分类" style="width: 200px">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品价格" prop="price">
          <el-input v-model="form.price" placeholder="请输入菜品价格" style="width: 200px"/>
        </el-form-item>

        <el-divider content-position="center">口味做法配置</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDishFlavor">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDishFlavor">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="dishFlavorList" :row-class-name="rowDishFlavorIndex"
                  @selection-change="handleDishFlavorSelectionChange" ref="dishFlavor" :key="randomKey">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="口味名称" prop="name" width="500px">
            <template slot-scope="scope">
              <div>
                <el-select v-model="scope.row.name" placeholder="请选择口味" @change="aa" style="width: 125px">
                  <el-option label="甜度" value="甜度"></el-option>
                  <el-option label="温度" value="温度"></el-option>
                  <el-option label="忌口" value="忌口"></el-option>
                  <el-option label="辣度" value="辣度"></el-option>
                </el-select>
              </div>
              <el-tag v-if="scope.row.name=='甜度'"
                      :key="tag"
                      v-for="tag in tags1"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(tag)">
                {{tag}}
              </el-tag>
              <el-tag v-if="scope.row.name=='温度'"
                      :key="tag"
                      v-for="tag in tags2"
                      closable
                      :disable-transitions="false"
                      @close="handleClose2(tag)">
                {{tag}}
              </el-tag>
              <el-tag v-if="scope.row.name=='忌口'"
                      :key="tag"
                      v-for="tag in tags3"
                      closable
                      :disable-transitions="false"
                      @close="handleClose3(tag)">
                {{tag}}
              </el-tag>
              <el-tag v-if="scope.row.name=='辣度'"
                      :key="tag"
                      v-for="tag in tags4"
                      closable
                      :disable-transitions="false"
                      @close="handleClose4(tag)">
                {{tag}}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm1"
                @blur="handleInputConfirm1">
              </el-input>
            </template>
          </el-table-column>
        </el-table>
        <el-form-item label="图片">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="描述信息" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入描述信息" style="width: 200px"/>
        </el-form-item>
        <el-form-item label="创建人" prop="createUser">
          <el-input v-model="form.createUser" placeholder="请输入创建人" style="width: 200px"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

  import {
    listDish,
    getDish,
    delDish,
    addDish,
    updateDish,
    plqs,
    plts,
    updateStatus,
    getDishList
  } from "@/api/dish/dish";

  export default {
    name: "Dish",
    data() {
      return {
        randomKey: Math.random(),
        tags1: ['无糖', '少糖', '半躺', '多糖', '全糖'],
        tags2: ['热饮', '常温', '去冰', '少冰', '多冰'],
        tags3: ['不要葱', '不要蒜', '不要香菜', '不要辣'],
        tags4: ['不辣', '微辣', '中辣', '重辣'],
        inputVisible: false,
        inputValue: '',
        options: [],
        updateDish: {
          id: 0,
          status: 0
        },
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedDishFlavor: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 菜品管理表格数据
        dishList: [],
        // 菜品口味关系表格数据
        dishFlavorList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
        },
        // 表单参数
        form: {},

        // 表单校验
        rules: {
          name: [
            {required: true, message: "菜品名称不能为空", trigger: "blur"}
          ],
          categoryId: [
            {required: true, message: "菜品分类id不能为空", trigger: "change"}
          ],
          price: [
            {required: true, message: "菜品价格不能为空", trigger: "blur"}
          ],
          image: [
            {required: true, message: "图片不能为空", trigger: "blur"}
          ],
        }
      };
    },
    created() {
      this.getList();
    },
    computed: {
      v() {
        return Math.random();
      }
    },
    methods: {
      handleClose(tag) {
        this.tags1.splice(this.tags1.indexOf(tag), 1);
        this.randomKey = Math.random();
      },
      handleClose2(tag) {
        this.tags2.splice(this.tags2.indexOf(tag), 1);
        this.randomKey = Math.random();
      },
      handleClose3(tag) {
        this.tags3.splice(this.tags3.indexOf(tag), 1);
        this.randomKey = Math.random();
      },
      handleClose4(tag) {
        this.tags4.splice(this.tags4.indexOf(tag), 1);
        this.randomKey = Math.random();
      },
      aa() {
        this.tags1 = ['无糖', '少糖', '半躺', '多糖', '全糖'];
        this.tags2 = ['热饮', '常温', '去冰', '少冰', '多冰'];
        this.tags3 = ['不要葱', '不要蒜', '不要香菜', '不要辣'];
        this.tags4 = ['不辣', '微辣', '中辣', '重辣'];
        this.randomKey = Math.random()
      },
      handleInputConfirm1() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.tags1.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      updateStatus(data) {
        if (data.status == 0) {
          this.updateDish.status = 1
        }
        if (data.status == 1) {
          this.updateDish.status = 0
        }
        this.updateDish.id = data.id;
        updateStatus(this.updateDish);
        this.getList();
        this.$modal.msgSuccess("修改成功");
      },
      /** 查询菜品管理列表 */
      getList() {
        this.loading = true;
        listDish(this.queryParams).then(response => {
          this.dishList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          categoryId: null,
          value: [],
          price: null,
          code: null,
          image: null,
          description: null,
          sort: null,
          createTime: null,
          updateTime: null,
          createUser: null,
          updateUser: null,
          isDeleted: null
        };
        this.dishFlavorList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.disable1 = false;
        this.disable2 = false;
        this.disable3 = false;
        this.disable4 = false;
        this.open = true;
        this.title = "添加菜品管理";
        getDishList().then(response => {
          this.options = response.rows;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getDish(id).then(response => {
          this.form = response.data;
          this.dishFlavorList = response.data.dishFlavorList;
          this.open = true;
          this.title = "修改菜品管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.dishFlavorList = this.dishFlavorList;
            if (this.form.id != null) {
              updateDish(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              // for (let i = 0; i < this.dishFlavorList.length; i++) {
              //   if (this.dishFlavorList[i].name=="甜度") {
              //       this.form.value=this.tags2;
              //   }
              //   if (this.dishFlavorList[i].name=='温度') {
              //     this.form.value=this.tags2;
              //   }
              //   if (this.dishFlavorList[i].name=='忌口') {
              //     this.form.value=this.tags3;
              //   }
              //   if (this.dishFlavorList[i].name=="辣度") {
              //     this.form.value=this.tags4;
              //   }
              // }
              // console.log(this.form.value)
              addDish(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除菜品管理编号为"' + ids + '"的数据项？').then(function () {
          return delDish(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      plqs(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认起售菜品管理编号为"' + ids + '"的数据项？').then(function () {
          return plqs(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("起售成功");
        }).catch(() => {
        });
      },
      plts(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认停售菜品管理编号为"' + ids + '"的数据项？').then(function () {
          return plts(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("停售成功");
        }).catch(() => {
        });
      },
      /** 菜品口味关系序号 */
      rowDishFlavorIndex({row, rowIndex}) {
        row.index = rowIndex + 1;
      },
      /** 菜品口味关系添加按钮操作 */
      handleAddDishFlavor() {
        if (this.dishFlavorList.length == 4) {
          alert("最多只能添加四个");
          return;
        }
        let obj = {};
        obj.name = "";
        obj.value = "";
        this.dishFlavorList.push(obj);
      },
      /** 菜品口味关系删除按钮操作 */
      handleDeleteDishFlavor() {
        if (this.checkedDishFlavor.length == 0) {
          this.$modal.msgError("请先选择要删除的菜品口味关系数据");
        } else {
          const dishFlavorList = this.dishFlavorList;
          const checkedDishFlavor = this.checkedDishFlavor;
          this.dishFlavorList = dishFlavorList.filter(function (item) {
            return checkedDishFlavor.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleDishFlavorSelectionChange(selection) {
        this.checkedDishFlavor = selection.map(item => item.index)
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('dish/dish/export', {
          ...this.queryParams
        }, `dish_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }

  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }

  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
